import { Component, ViewContainerRef, ViewChild, Input, ComponentRef, ComponentFactoryResolver, ChangeDetectorRef } from '@angular/core';

// 动态渲染的指令
@Component({
    selector: 'tab-render',
    template: `<div #target></div>` 
})
export class TabDirective {
    // 从模板中获取对应的元素（通过设置查询的条件，把视图转换为不同的实例）
    @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
    @Input() type;
    cmpRef: ComponentRef<any>;
    private isViewInitialized: boolean = false;

    constructor(private componentFactoryResolver: ComponentFactoryResolver,
        private cdRef: ChangeDetectorRef) { }

    updateComponent() {
        if (!this.isViewInitialized) {
            return;
        }
        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
        // 动态创建组件的服务，将一个组件实例呈现到另一个组件视图上
        let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
        this.cmpRef = this.target.createComponent(factory);
        this.cdRef.detectChanges();
    }

    ngOnInit() {
        this.updateComponent();
    }

    ngOnChanges() {
        this.updateComponent();
    }

    ngAfterViewInit() {
        this.isViewInitialized = true;
        this.updateComponent();
    }

    ngOnDestroy() {
        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
    }
}

